import React, { Component } from 'react'
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { Avatar, Menu, Dropdown } from 'antd';
import { quitReq, getUserReq } from '@/utils/request'
import { USERCHANGE } from '@/store/actionType'

const mapStateToProps = (state, ownProps) => {
  return {
    avatar: state.getIn(['user', 'obj', 'avatar'])
  }
}
const mapDispatchToProps = {
  getUser: () => {
    return getUserReq().then((res) => {
      if (res.code === 200) {
        return {
          type: USERCHANGE,
          payload: res.result
        }
      }
    })
  }
}
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class TopUser extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dropMenu: <Menu onClick={this.userClicked}>
        <Menu.Item key='/user'>
          个人信息
      </Menu.Item>
        <Menu.Item key='userexit'>
          退出
      </Menu.Item>
      </Menu>
    }

  }
  componentDidMount() {
    this.props.getUser()
  }
  render() {
    // 判断是否登录
    const flag = sessionStorage.getItem('bloger')//token或者null
    return flag ? (
      <div >
        {/* 包个div,不会出现距离太远 */}
        <Dropdown overlay={this.state.dropMenu}>
          <Avatar size="large" src={this.props.avatar || '/topaz-blog/qq.jpg'} style={{ background: '#fff' }} />
        </Dropdown>
      </div>
    ) : (<div style={{ color: "#B4CDCD" }}>
      <span onClick={() => this.LinkTo('/login')}>
        登录
    </span>
      <span style={{ padding: '0 10px' }}>|</span>
      <span onClick={() => this.LinkTo('/register')}>
        注册
    </span>
    </div>)
  }
  LinkTo = (targetPath) => {
    this.props.history && this.props.history.push(targetPath)
  }
  userClicked = (item) => {
    switch (item.key) {
      case '/user':
        this.props.history.push(item.key)
        break
      case 'userexit':
        quitReq().then(res => {
          if (res.code) {
            sessionStorage.removeItem('bloger')
            sessionStorage.removeItem('email')
            this.props.history.push('/')
          }
        })
        break
      default:
        break
    }
  }
}


export default TopUser